var express = require("express");
const app = express();
const verifyToken = require("../utils/verifyToken");
var router = express.Router();
const sqlconfig = require("../mysql/config");
const { createResponse } = require("../utils/responseHelper");

// 辅助函数：将下划线命名转换为驼峰命名
function toCamelCase(str) {
  return str.replace(/_([a-z])/g, function (g) {
    return g[1].toUpperCase();
  });
}

// 辅助函数：递归转换对象的键为驼峰命名
function convertToCamelCase(obj) {
  if (Array.isArray(obj)) {
    return obj.map(convertToCamelCase);
  } else if (obj !== null && typeof obj === "object") {
    return Object.keys(obj).reduce((result, key) => {
      result[toCamelCase(key)] = convertToCamelCase(obj[key]);
      return result;
    }, {});
  }
  return obj;
}

// 创建菜单
router.post("/createMenu", verifyToken, function (req, res, next) {
  try {
    const {
      menuType,
      menuName,
      parentId,
      path,
      component,
      icon,
      sortOrder,
      isRoute,
      isHidden,
      isCached,
      permissions,
    } = req.body;

    // 输入验证
    if (!menuType || !menuName) {
      return createResponse(
        res,
        "SERVER_ERROR",
        null,
        "菜单类型和菜单名称不能为空"
      );
    }

    if (menuType !== "TOP_MENU" && menuType !== "SUB_MENU") {
      return createResponse(
        res,
        "SERVER_ERROR",
        null,
        "菜单类型必须是 TOP_MENU 或 SUB_MENU"
      );
    }

    if (menuType === "SUB_MENU" && !parentId) {
      return createResponse(
        res,
        "SERVER_ERROR",
        null,
        "子菜单必须选择上级菜单"
      );
    }

    // 检查菜单名和路径是否重复
    const checkDuplicateSql =
      "SELECT id FROM menus WHERE menu_name = ? OR (path = ? AND path IS NOT NULL)";
    sqlconfig.query(checkDuplicateSql, [menuName, path], (err, result) => {
      if (err) {
        return createResponse(res, "SERVER_ERROR", null, err.toString());
      }
      if (result.length > 0) {
        return createResponse(res, "SERVER_ERROR", null, "菜单名或路径已存在");
      }

      // 如果是子菜单，检查父菜单是否存在
      if (menuType === "SUB_MENU") {
        const checkParentSql = "SELECT id FROM menus WHERE id = ?";
        sqlconfig.query(checkParentSql, [parentId], (err, result) => {
          if (err) {
            return createResponse(res, "SERVER_ERROR", null, err.toString());
          }
          if (result.length === 0) {
            return createResponse(
              res,
              "SERVER_ERROR",
              null,
              "指定的父菜单不存在"
            );
          }
          // 父菜单存在，继续创建子菜单
          insertMenu();
        });
      } else {
        // 如果是顶级菜单，直接创建
        insertMenu();
      }
    });

    function insertMenu() {
      // 插入新菜单
      const insertSql = `
        INSERT INTO menus 
        (parent_id, menu_type, menu_name, path, component, icon, sort_order, is_route, is_hidden, is_cached, permissions) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
      `;

      const values = [
        menuType === "SUB_MENU" ? parentId : null,
        menuType,
        menuName,
        path || null,
        component || null,
        icon || null,
        sortOrder || 0,
        isRoute ? 1 : 0,
        isHidden ? 1 : 0,
        isCached ? 1 : 0,
        permissions || null,
      ];

      sqlconfig.query(insertSql, values, (err, result) => {
        if (err) {
          return createResponse(res, "SERVER_ERROR", null, err.toString());
        }

        createResponse(res, "SUCCESS", { id: result.insertId }, "菜单创建成功");
      });
    }
  } catch (error) {
    createResponse(res, "SERVER_ERROR", null, error.toString());
  }
});

// 获取父级菜单
router.get("/getParentMenu", verifyToken, (req, res) => {
  try {
    // SQL 查询来获取所有父级菜单
    const sql = `
      SELECT id, menu_name, path, icon, sort_order
      FROM menus
      WHERE parent_id IS NULL OR parent_id = 0
      ORDER BY sort_order ASC
    `;

    sqlconfig.query(sql, (err, results) => {
      if (err) {
        console.error("获取父级菜单时出错:", err);
        return createResponse(res, "SERVER_ERROR", null, "获取父级菜单失败");
      }

      // 处理结果并转换为驼峰命名
      const parentMenus = convertToCamelCase(results);

      createResponse(res, "SUCCESS", parentMenus, "获取父级菜单成功");
    });
  } catch (error) {
    console.error("获取父级菜单时发生异常:", error);
    createResponse(res, "SERVER_ERROR", null, "获取父级菜单时发生异常");
  }
});

// 获取菜单列表
router.get("/getMenuList", verifyToken, (req, res) => {
  try {
    // SQL 查询来获取所有菜单
    const sql = `
      SELECT id, parent_id, menu_type, menu_name, path, component, icon, sort_order, is_route, is_hidden, is_cached, permissions
      FROM menus
      ORDER BY sort_order ASC
    `;

    sqlconfig.query(sql, (err, results) => {
      if (err) {
        console.error("获取菜单列表时出错:", err);
        return createResponse(res, "SERVER_ERROR", null, "获取菜单列表失败");
      }

      // 将查询结果转换为树形结构，并转换为驼峰命名
      const menuTree = convertToCamelCase(buildMenuTree(results));

      createResponse(res, "SUCCESS", menuTree, "获取菜单列表成功");
    });
  } catch (error) {
    console.error("获取菜单列表时发生异常:", error);
    createResponse(res, "SERVER_ERROR", null, "获取菜单列表时发生异常");
  }
});

// 修改菜单
router.put("/updateMenu/:id", verifyToken, function (req, res, next) {
  try {
    const menuId = req.params.id;
    const {
      menuType,
      menuName,
      parentId,
      path,
      component,
      icon,
      sortOrder,
      isRoute,
      isHidden,
      isCached,
      permissions,
    } = req.body;

    // 检查菜单是否存在
    const checkMenuSql = "SELECT id FROM menus WHERE id = ?";
    sqlconfig.query(checkMenuSql, [menuId], (err, result) => {
      if (err) {
        return createResponse(res, "SERVER_ERROR", null, err.toString());
      }
      if (result.length === 0) {
        return createResponse(res, "SERVER_ERROR", null, "菜单不存在");
      }

      // 更新菜单
      const updateSql = `
        UPDATE menus 
        SET menu_type = ?, menu_name = ?, parent_id = ?, path = ?, component = ?, 
            icon = ?, sort_order = ?, is_route = ?, is_hidden = ?, is_cached = ?, permissions = ?
        WHERE id = ?
      `;

      const values = [
        menuType,
        menuName,
        parentId,
        path,
        component,
        icon,
        sortOrder,
        isRoute ? 1 : 0,
        isHidden ? 1 : 0,
        isCached ? 1 : 0,
        permissions,
        menuId,
      ];

      sqlconfig.query(updateSql, values, (err, result) => {
        if (err) {
          return createResponse(res, "SERVER_ERROR", null, err.toString());
        }

        createResponse(res, "SUCCESS", { id: menuId }, "菜单更新成功");
      });
    });
  } catch (error) {
    createResponse(res, "SERVER_ERROR", null, error.toString());
  }
});

// 删除菜单
router.delete("/deleteMenu/:id", verifyToken, function (req, res, next) {
  try {
    const menuId = req.params.id;

    // 检查是否有子菜单
    const checkChildrenSql = "SELECT id FROM menus WHERE parent_id = ?";
    sqlconfig.query(checkChildrenSql, [menuId], (err, result) => {
      if (err) {
        return createResponse(res, "SERVER_ERROR", null, err.toString());
      }
      if (result.length > 0) {
        return createResponse(
          res,
          "SERVER_ERROR",
          null,
          "该菜单有子菜单，无法删除"
        );
      }

      // 删除菜单
      const deleteSql = "DELETE FROM menus WHERE id = ?";
      sqlconfig.query(deleteSql, [menuId], (err, result) => {
        if (err) {
          return createResponse(res, "SERVER_ERROR", null, err.toString());
        }

        createResponse(res, "SUCCESS", { id: menuId }, "菜单删除成功");
      });
    });
  } catch (error) {
    createResponse(res, "SERVER_ERROR", null, error.toString());
  }
});

// 辅助函数：构建菜单树
function buildMenuTree(menus, parentId = null) {
  return menus
    .filter((menu) => menu.parent_id === parentId)
    .map((menu) => {
      const children = buildMenuTree(menus, menu.id);
      return {
        ...menu,
        children: children.length > 0 ? children : undefined,
      };
    })
    .sort((a, b) => a.sort_order - b.sort_order);
}

module.exports = router;
